package persistence

import (
	"fmt"
	"os"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"tools.hezhuyun/checker/domain/repository"
)

type Repositories struct {
	File   repository.FileRepository
	Folder repository.FolderRepository
	db     *gorm.DB
}

func NewRepositories() (*Repositories, error) {
	db, err := DBConnection()
	return &Repositories{
		File:   NewFileRepository(db),
		Folder: NewFolderRepository(db),
		db:     db,
	}, err
}

func DBConnection() (*gorm.DB, error) {
	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
		os.Getenv("DB_USER"),
		os.Getenv("DB_PASS"),
		os.Getenv("DB_HOST"),
		os.Getenv("DB_PORT"),
		os.Getenv("DB_NAME"),
	)
	return gorm.Open(mysql.New(mysql.Config{
		DSN: dsn,
	}), &gorm.Config{})
}
